package service

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/config"
	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonpayModels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"github.com/redis/go-redis/v9"
	"github.com/shopspring/decimal"
)

// StatisticsService 统计服务
type StatisticsService struct {
	client *photonpay.PhotonPayClient
}

// NewStatisticsService 创建统计服务
func NewStatisticsService(client *photonpay.PhotonPayClient) *StatisticsService {
	return &StatisticsService{
		client: photonpay.GetPhotonPayClient(config.GetPlatformConfig()),
	}
}

// TransactionStatistics 交易统计
type TransactionStatistics struct {
	TotalAmount   float64 `json:"total_amount"`   // 总交易金额
	TotalCount    int64   `json:"total_count"`    // 总交易笔数
	SuccessAmount float64 `json:"success_amount"` // 成功交易金额
	SuccessCount  int64   `json:"success_count"`  // 成功交易笔数
	FailedAmount  float64 `json:"failed_amount"`  // 失败交易金额
	FailedCount   int64   `json:"failed_count"`   // 失败交易笔数
	PendingAmount float64 `json:"pending_amount"` // 待处理交易金额
	PendingCount  int64   `json:"pending_count"`  // 待处理交易笔数
	AverageAmount float64 `json:"average_amount"` // 平均交易金额
	SuccessRate   float64 `json:"success_rate"`   // 成功率
}

// GetTransactionStatistics 获取交易统计
func (s *StatisticsService) GetTransactionStatistics(ctx context.Context, startTime, endTime time.Time) (*TransactionStatistics, error) {
	// TODO: 实现从实际数据源获取交易统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := &TransactionStatistics{
		TotalAmount:   100000.00,
		TotalCount:    1000,
		SuccessAmount: 90000.00,
		SuccessCount:  900,
		FailedAmount:  5000.00,
		FailedCount:   50,
		PendingAmount: 5000.00,
		PendingCount:  50,
		AverageAmount: 100.00,
		SuccessRate:   90.00,
	}
	return stats, nil
}

// DailyTransactionStats 每日交易统计
type DailyTransactionStats struct {
	Date          time.Time `json:"date"`           // 日期
	TotalAmount   float64   `json:"total_amount"`   // 总金额
	TotalCount    int64     `json:"total_count"`    // 总笔数
	SuccessAmount float64   `json:"success_amount"` // 成功金额
	SuccessCount  int64     `json:"success_count"`  // 成功笔数
}

// GetDailyTransactionStats 获取每日交易统计
func (s *StatisticsService) GetDailyTransactionStats(ctx context.Context, startTime, endTime time.Time) ([]DailyTransactionStats, error) {
	// TODO: 实现从实际数据源获取每日交易统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := []DailyTransactionStats{
		{
			Date:          time.Now().AddDate(0, 0, -1),
			TotalAmount:   10000.00,
			TotalCount:    100,
			SuccessAmount: 9000.00,
			SuccessCount:  90,
		},
		{
			Date:          time.Now(),
			TotalAmount:   15000.00,
			TotalCount:    150,
			SuccessAmount: 13500.00,
			SuccessCount:  135,
		},
	}
	return stats, nil
}

// UserStatistics 用户统计
type UserStatistics struct {
	TotalUsers      int64 `json:"total_users"`      // 总用户数
	ActiveUsers     int64 `json:"active_users"`     // 活跃用户数
	NewUsers        int64 `json:"new_users"`        // 新增用户数
	TotalMerchants  int64 `json:"total_merchants"`  // 总商户数
	NewMerchants    int64 `json:"new_merchants"`    // 新增商户数
	ActiveMerchants int64 `json:"active_merchants"` // 活跃商户数
}

// GetUserStatistics 获取用户统计
func (s *StatisticsService) GetUserStatistics(ctx context.Context, startTime, endTime time.Time) (*UserStatistics, error) {
	// TODO: 实现从实际数据源获取用户统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := &UserStatistics{
		TotalUsers:      1000,
		ActiveUsers:     500,
		NewUsers:        100,
		TotalMerchants:  200,
		NewMerchants:    20,
		ActiveMerchants: 150,
	}
	return stats, nil
}

// PaymentMethodStats 支付方式统计
type PaymentMethodStats struct {
	Method        string  `json:"method"`         // 支付方式
	TotalAmount   float64 `json:"total_amount"`   // 总金额
	TotalCount    int64   `json:"total_count"`    // 总笔数
	SuccessAmount float64 `json:"success_amount"` // 成功金额
	SuccessCount  int64   `json:"success_count"`  // 成功笔数
	SuccessRate   float64 `json:"success_rate"`   // 成功率
}

// GetPaymentMethodStats 获取支付方式统计
func (s *StatisticsService) GetPaymentMethodStats(ctx context.Context, startTime, endTime time.Time) ([]PaymentMethodStats, error) {
	// TODO: 实现从实际数据源获取支付方式统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := []PaymentMethodStats{
		{
			Method:        "alipay",
			TotalAmount:   50000.00,
			TotalCount:    500,
			SuccessAmount: 45000.00,
			SuccessCount:  450,
			SuccessRate:   90.00,
		},
		{
			Method:        "wechat",
			TotalAmount:   30000.00,
			TotalCount:    300,
			SuccessAmount: 28500.00,
			SuccessCount:  285,
			SuccessRate:   95.00,
		},
	}
	return stats, nil
}

// RegionStats 地区统计
type RegionStats struct {
	Region        string  `json:"region"`         // 地区
	TotalAmount   float64 `json:"total_amount"`   // 总金额
	TotalCount    int64   `json:"total_count"`    // 总笔数
	SuccessAmount float64 `json:"success_amount"` // 成功金额
	SuccessCount  int64   `json:"success_count"`  // 成功笔数
	SuccessRate   float64 `json:"success_rate"`   // 成功率
}

// GetRegionStats 获取地区统计
func (s *StatisticsService) GetRegionStats(ctx context.Context, startTime, endTime time.Time) ([]RegionStats, error) {
	// TODO: 实现从实际数据源获取地区统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := []RegionStats{
		{
			Region:        "CN",
			TotalAmount:   60000.00,
			TotalCount:    600,
			SuccessAmount: 57000.00,
			SuccessCount:  570,
			SuccessRate:   95.00,
		},
		{
			Region:        "US",
			TotalAmount:   20000.00,
			TotalCount:    200,
			SuccessAmount: 18000.00,
			SuccessCount:  180,
			SuccessRate:   90.00,
		},
	}
	return stats, nil
}

// AmountRangeStats 交易金额区间统计
type AmountRangeStats struct {
	Range         string  `json:"range"`          // 金额区间
	TotalAmount   float64 `json:"total_amount"`   // 总金额
	TotalCount    int64   `json:"total_count"`    // 总笔数
	SuccessAmount float64 `json:"success_amount"` // 成功金额
	SuccessCount  int64   `json:"success_count"`  // 成功笔数
	SuccessRate   float64 `json:"success_rate"`   // 成功率
}

// GetAmountRangeStats 获取交易金额区间统计
func (s *StatisticsService) GetAmountRangeStats(ctx context.Context, startTime, endTime time.Time) ([]AmountRangeStats, error) {
	// TODO: 实现从实际数据源获取交易金额区间统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := []AmountRangeStats{
		{
			Range:         "0-100",
			TotalAmount:   5000.00,
			TotalCount:    100,
			SuccessAmount: 4500.00,
			SuccessCount:  90,
			SuccessRate:   90.00,
		},
		{
			Range:         "100-1000",
			TotalAmount:   50000.00,
			TotalCount:    100,
			SuccessAmount: 47500.00,
			SuccessCount:  95,
			SuccessRate:   95.00,
		},
	}
	return stats, nil
}

// RefundStats 退款统计
type RefundStats struct {
	TotalAmount   float64 `json:"total_amount"`   // 总退款金额
	TotalCount    int64   `json:"total_count"`    // 总退款笔数
	SuccessAmount float64 `json:"success_amount"` // 成功退款金额
	SuccessCount  int64   `json:"success_count"`  // 成功退款笔数
	FailedAmount  float64 `json:"failed_amount"`  // 失败退款金额
	FailedCount   int64   `json:"failed_count"`   // 失败退款笔数
	PendingAmount float64 `json:"pending_amount"` // 待处理退款金额
	PendingCount  int64   `json:"pending_count"`  // 待处理退款笔数
	SuccessRate   float64 `json:"success_rate"`   // 成功率
}

// GetRefundStats 获取退款统计
func (s *StatisticsService) GetRefundStats(ctx context.Context, startTime, endTime time.Time) (*RefundStats, error) {
	// TODO: 实现从实际数据源获取退款统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := &RefundStats{
		TotalAmount:   10000.00,
		TotalCount:    100,
		SuccessAmount: 8000.00,
		SuccessCount:  80,
		FailedAmount:  1000.00,
		FailedCount:   10,
		PendingAmount: 1000.00,
		PendingCount:  10,
		SuccessRate:   80.00,
	}
	return stats, nil
}

// FeeStats 手续费统计
type FeeStats struct {
	TotalFee    float64            `json:"total_fee"`     // 总手续费
	TotalCount  int64              `json:"total_count"`   // 总笔数
	AverageFee  float64            `json:"average_fee"`   // 平均手续费
	MaxFee      float64            `json:"max_fee"`       // 最大手续费
	MinFee      float64            `json:"min_fee"`       // 最小手续费
	FeeByMethod map[string]float64 `json:"fee_by_method"` // 各支付方式手续费
	FeeByRegion map[string]float64 `json:"fee_by_region"` // 各地区手续费
}

// GetFeeStats 获取手续费统计
func (s *StatisticsService) GetFeeStats(ctx context.Context, startTime, endTime time.Time) (*FeeStats, error) {
	// TODO: 实现从实际数据源获取手续费统计数据
	// 这里返回模拟数据，实际实现时需要替换为真实数据
	stats := &FeeStats{
		TotalFee:   1000.00,
		TotalCount: 1000,
		AverageFee: 1.00,
		MaxFee:     10.00,
		MinFee:     0.10,
		FeeByMethod: map[string]float64{
			"alipay": 500.00,
			"wechat": 500.00,
		},
		FeeByRegion: map[string]float64{
			"CN": 600.00,
			"US": 400.00,
		},
	}
	return stats, nil
}

// CardStatistics 卡片统计
type CardStatistics struct {
	TotalCards      int64              `json:"total_cards"`       // 总开卡数量
	ActiveCards     int64              `json:"active_cards"`      // 可用卡数量
	CancelledCards  int64              `json:"cancelled_cards"`   // 销卡数量
	FrozenCards     int64              `json:"frozen_cards"`      // 冻结卡数量
	TotalBalance    float64            `json:"total_balance"`     // 总卡内余额
	AverageBalance  float64            `json:"average_balance"`   // 平均卡内余额
	MaxBalance      float64            `json:"max_balance"`       // 最大卡内余额
	MinBalance      float64            `json:"min_balance"`       // 最小卡内余额
	BalanceByStatus map[string]float64 `json:"balance_by_status"` // 各状态卡片的余额统计
}

// HlPayEnhancedStatistics HlPay增强统计数据
type HlPayEnhancedStatistics struct {
	CardStatistics   CardStatistics         `json:"card_statistics"`    // 基础卡片统计
	TotalCardBalance float64                `json:"total_card_balance"` // 卡内总金额
	AccountBalance   float64                `json:"account_balance"`    // 账户余额
	TotalRecharge    float64                `json:"total_recharge"`     // 总充值金额
	TransactionCount int64                  `json:"transaction_count"`  // 交易笔数
	ChargebackRate   float64                `json:"chargeback_rate"`    // 当月拒付率
	IssuedCards      int64                  `json:"issued_cards"`       // 已开卡数
	BalanceByStatus  map[string]float64     `json:"balance_by_status"`  // 各状态卡片的余额统计
	TransactionStats map[string]interface{} `json:"transaction_stats"`  // 交易统计详情
}

// GetCardStatistics 获取卡片统计
func (s *StatisticsService) GetCardStatistics(ctx context.Context, startTime, endTime time.Time, matrixAccount string) (*CardStatistics, error) {
	// 生成缓存key
	cacheKey := fmt.Sprintf("card_stats:%s", matrixAccount)
	log.Printf("Attempting to get card statistics from cache with key: %s", cacheKey)

	// 尝试从Redis获取缓存数据
	cachedData, err := database.Get(ctx, cacheKey)
	if err != nil {
		if err != redis.Nil {
			log.Printf("Error getting data from Redis: %v", err)
		} else {
			log.Printf("Cache miss for key: %s", cacheKey)
		}
	} else if cachedData != "" {
		log.Printf("Cache hit for key: %s", cacheKey)
		var stats CardStatistics
		if err := json.Unmarshal([]byte(cachedData), &stats); err == nil {
			log.Printf("Successfully unmarshaled cached data")
			return &stats, nil
		} else {
			log.Printf("Error unmarshaling cached data: %v", err)
		}
	}

	// 缓存未命中，从API获取数据
	log.Printf("Fetching fresh data from PhotonPay API")

	// 清除旧缓存以确保获取最新数据
	database.Delete(ctx, cacheKey)
	var stats CardStatistics
	stats.BalanceByStatus = make(map[string]float64)

	// 从photonpay获取所有卡片的余额信息
	pageIndex := 1
	pageSize := 1000
	var allCards []photonpayModels.CardInfo

	for {
		params := photonpayModels.CardListQueryParams{
			PageIndex:     pageIndex,
			PageSize:      pageSize,
			MatrixAccount: matrixAccount,
		}

		cardList, err := services.GetCardList(ctx, s.client, params)
		if err != nil {
			return nil, fmt.Errorf("failed to get card list: %v", err)
		}

		allCards = append(allCards, cardList.Data...)

		// 如果返回的数据少于pageSize，说明已经获取完所有数据
		if len(cardList.Data) < pageSize {
			break
		}

		pageIndex++
	}

	// 统计卡片数量和余额
	stats.TotalCards = int64(len(allCards))
	for _, card := range allCards {
		// 统计各状态卡片数量
		switch strings.ToLower(card.CardStatus) {
		case "normal":
			stats.ActiveCards++
		case "cancelled", "closed":
			stats.CancelledCards++
		case "frozen":
			stats.FrozenCards++
		}

		// 统计余额
		balance := card.CardBalance
		stats.TotalBalance += balance

		// 标准化状态名称用于余额统计
		normalizedStatus := strings.ToLower(card.CardStatus)
		switch normalizedStatus {
		case "cancelled", "closed":
			normalizedStatus = "cancelled"
		}
		stats.BalanceByStatus[normalizedStatus] += balance

		// 更新最大和最小余额
		if stats.MaxBalance < balance {
			stats.MaxBalance = balance
		}
		if stats.MinBalance == 0 || stats.MinBalance > balance {
			stats.MinBalance = balance
		}
	}

	// 计算平均余额
	if stats.TotalCards > 0 {
		stats.AverageBalance = stats.TotalBalance / float64(stats.TotalCards)
	}

	// 将数据缓存到Redis，设置30秒的过期时间
	if data, err := json.Marshal(stats); err == nil {
		log.Printf("Caching data with key: %s", cacheKey)
		if err := database.SetWithExpiration(ctx, cacheKey, data, 30*time.Second); err != nil {
			log.Printf("Error caching data: %v", err)
		} else {
			log.Printf("Successfully cached data")
		}
	} else {
		log.Printf("Error marshaling data for cache: %v", err)
	}

	return &stats, nil
}

// GetHlPayCardStatistics 获取HlPay平台的卡片统计数据
func (s *StatisticsService) GetHlPayCardStatistics(ctx context.Context, startTime, endTime time.Time, platformInfo *middleware.PlatformInfo) (*CardStatistics, error) {
	// 生成缓存key
	cacheKey := fmt.Sprintf("hlpay_card_stats:%s", platformInfo.MatrixAccount)
	log.Printf("Attempting to get HlPay card statistics from cache with key: %s", cacheKey)

	// 尝试从Redis获取缓存数据
	cachedData, err := database.Get(ctx, cacheKey)
	if err != nil {
		if err != redis.Nil {
			log.Printf("Error getting data from Redis: %v", err)
		} else {
			log.Printf("Cache miss for key: %s", cacheKey)
		}
	} else if cachedData != "" {
		log.Printf("Cache hit for key: %s", cacheKey)
		var stats CardStatistics
		if err := json.Unmarshal([]byte(cachedData), &stats); err == nil {
			log.Printf("Successfully unmarshaled cached data")
			return &stats, nil
		} else {
			log.Printf("Error unmarshaling cached data: %v", err)
		}
	}

	// 缓存未命中，从本地数据库获取数据
	log.Printf("Fetching fresh data from local database for HlPay")

	// 清除旧缓存以确保获取最新数据
	database.Delete(ctx, cacheKey)
	var stats CardStatistics
	stats.BalanceByStatus = make(map[string]float64)

	// 从本地数据库获取HlPay平台的卡片信息
	var userCards []models.UserCard
	query := database.DB.Where("platform = ?", "hlpay")

	// 根据矩阵账户过滤数据
	if strings.HasPrefix(platformInfo.MatrixAccount, "SUB") {
		// 子账号用户，只能看到自己的卡片
		query = query.Where("user_id IN (SELECT user_id FROM user_matrix_accounts WHERE matrix_account = ?)", platformInfo.MatrixAccount)
	} else {
		// 主账号用户，可以看到所有子账号的卡片
		query = query.Where("user_id IN (SELECT user_id FROM user_matrix_accounts WHERE matrix_account = ? OR matrix_account LIKE ?)",
			platformInfo.MatrixAccount, platformInfo.MatrixAccount+"%")
	}

	// 添加时间范围过滤
	if !startTime.IsZero() && !endTime.IsZero() {
		query = query.Where("created_at BETWEEN ? AND ?", startTime, endTime)
	}

	if err := query.Find(&userCards).Error; err != nil {
		return nil, fmt.Errorf("failed to get user cards from database: %v", err)
	}

	// 统计卡片数量和余额
	stats.TotalCards = int64(len(userCards))
	for _, card := range userCards {
		// 统计各状态卡片数量
		switch strings.ToLower(card.CardStatus) {
		case "normal":
			stats.ActiveCards++
		case "cancelled", "closed":
			stats.CancelledCards++
		case "frozen":
			stats.FrozenCards++
		}

		// 统计余额（TotalTransferAmount字段）
		balance := card.TotalTransferAmount.InexactFloat64()
		stats.TotalBalance += balance

		// 标准化状态名称用于余额统计
		normalizedStatus := strings.ToLower(card.CardStatus)
		switch normalizedStatus {
		case "cancelled", "closed":
			normalizedStatus = "cancelled"
		}
		stats.BalanceByStatus[normalizedStatus] += balance

		// 更新最大和最小余额
		if stats.MaxBalance < balance {
			stats.MaxBalance = balance
		}
		if stats.MinBalance == 0 || stats.MinBalance > balance {
			stats.MinBalance = balance
		}
	}

	// 计算平均余额
	if stats.TotalCards > 0 {
		stats.AverageBalance = stats.TotalBalance / float64(stats.TotalCards)
	}

	// 将数据缓存到Redis，设置30秒的过期时间
	if data, err := json.Marshal(stats); err == nil {
		log.Printf("Caching data with key: %s", cacheKey)
		if err := database.SetWithExpiration(ctx, cacheKey, data, 30*time.Second); err != nil {
			log.Printf("Error caching data: %v", err)
		} else {
			log.Printf("Successfully cached data")
		}
	} else {
		log.Printf("Error marshaling data for cache: %v", err)
	}

	return &stats, nil
}

// GetHlPayEnhancedStatistics 获取HlPay平台的增强统计数据（包含Redis交易数据）
func (s *StatisticsService) GetHlPayEnhancedStatistics(ctx context.Context, platformInfo *middleware.PlatformInfo) (*HlPayEnhancedStatistics, error) {
	// 生成缓存key
	cacheKey := fmt.Sprintf("hlpay_enhanced_stats:%s", platformInfo.MatrixAccount)
	log.Printf("Attempting to get HlPay enhanced statistics from cache with key: %s", cacheKey)

	// 尝试从Redis获取缓存数据
	cachedData, err := database.Get(ctx, cacheKey)
	if err != nil {
		if err != redis.Nil {
			log.Printf("Error getting data from Redis: %v", err)
		} else {
			log.Printf("Cache miss for key: %s", cacheKey)
		}
	} else if cachedData != "" {
		log.Printf("Cache hit for key: %s", cacheKey)
		var stats HlPayEnhancedStatistics
		if err := json.Unmarshal([]byte(cachedData), &stats); err == nil {
			log.Printf("Successfully unmarshaled cached data")
			return &stats, nil
		} else {
			log.Printf("Error unmarshaling cached data: %v", err)
		}
	}

	// 缓存未命中，获取增强统计数据
	log.Printf("Fetching fresh enhanced data for HlPay")

	// 清除旧缓存以确保获取最新数据
	database.Delete(ctx, cacheKey)

	stats := &HlPayEnhancedStatistics{
		BalanceByStatus:  make(map[string]float64),
		TransactionStats: make(map[string]interface{}),
	}

	// 1. 获取基础卡片统计
	cardStats, err := s.GetHlPayCardStatistics(ctx, time.Time{}, time.Time{}, platformInfo)
	if err != nil {
		log.Printf("Warning: failed to get card statistics: %v", err)
	} else {
		stats.CardStatistics = *cardStats
		// 设置卡内总金额和已开卡数
		stats.TotalCardBalance = cardStats.TotalBalance
		stats.IssuedCards = cardStats.TotalCards
		stats.BalanceByStatus = cardStats.BalanceByStatus
	}

	// 2. 从Redis获取交易数据统计
	if err := s.calculateTransactionStatsFromRedis(ctx, platformInfo, stats); err != nil {
		log.Printf("Warning: failed to calculate transaction stats from Redis: %v", err)
	}

	// 3. 计算账户余额
	if err := s.calculateAccountBalance(ctx, platformInfo, stats); err != nil {
		log.Printf("Warning: failed to calculate account balance: %v", err)
	}

	// 4. 计算当月拒付率
	if err := s.calculateMonthlyChargebackRate(ctx, platformInfo, stats); err != nil {
		log.Printf("Warning: failed to calculate monthly chargeback rate: %v", err)
	}

	// 将数据缓存到Redis，设置60秒的过期时间
	if data, err := json.Marshal(stats); err == nil {
		log.Printf("Caching enhanced data with key: %s", cacheKey)
		if err := database.SetWithExpiration(ctx, cacheKey, data, 60*time.Second); err != nil {
			log.Printf("Error caching enhanced data: %v", err)
		} else {
			log.Printf("Successfully cached enhanced data")
		}
	} else {
		log.Printf("Error marshaling enhanced data for cache: %v", err)
	}

	return stats, nil
}

// calculateTransactionStatsFromRedis 从Redis计算交易统计数据
func (s *StatisticsService) calculateTransactionStatsFromRedis(ctx context.Context, platformInfo *middleware.PlatformInfo, stats *HlPayEnhancedStatistics) error {
	// 获取用户ID列表
	var userIDs []int64
	query := database.DB.Model(&models.UserMatrixAccount{}).Select("user_id")

	if strings.HasPrefix(platformInfo.MatrixAccount, "SUB") {
		// 子账号用户，只能看到自己的卡片
		query = query.Where("matrix_account = ?", platformInfo.MatrixAccount)
	} else {
		// 主账号用户，可以看到所有子账号的卡片
		query = query.Where("matrix_account = ? OR matrix_account LIKE ?",
			platformInfo.MatrixAccount, platformInfo.MatrixAccount+"%")
	}

	if err := query.Find(&userIDs).Error; err != nil {
		return fmt.Errorf("failed to get user IDs: %v", err)
	}

	// 统计交易数据
	var totalAmount float64
	var transactionCount int64
	var rechargeAmount float64

	for _, userID := range userIDs {
		// 从Redis获取用户交易列表
		userTxListKey := fmt.Sprintf("hlpay_user_transactions:%d", userID)
		txIDs, err := database.RedisClient.ZRange(ctx, userTxListKey, 0, -1).Result()
		if err != nil {
			log.Printf("Warning: failed to get transactions for user %d: %v", userID, err)
			continue
		}

		for _, txID := range txIDs {
			// 获取交易详情
			txKey := fmt.Sprintf("hlpay_transaction:%s", txID)
			txData, err := database.Get(ctx, txKey)
			if err != nil {
				log.Printf("Warning: failed to get transaction %s: %v", txID, err)
				continue
			}

			// 解析交易数据
			var tx struct {
				Amount          string `json:"amount"`
				TransactionType string `json:"transactionType"`
				Status          string `json:"status"`
			}
			if err := json.Unmarshal([]byte(txData), &tx); err != nil {
				log.Printf("Warning: failed to unmarshal transaction %s: %v", txID, err)
				continue
			}

			// 解析金额
			amount, err := strconv.ParseFloat(tx.Amount, 64)
			if err != nil {
				log.Printf("Warning: failed to parse amount for transaction %s: %v", txID, err)
				continue
			}

			// 统计交易笔数和金额
			transactionCount++
			totalAmount += amount

			// 统计充值金额
			if strings.ToLower(tx.TransactionType) == "recharge" {
				rechargeAmount += amount
			}
		}
	}

	// 更新统计数据
	stats.TransactionCount = transactionCount
	stats.TotalRecharge = rechargeAmount
	stats.TransactionStats["total_amount"] = totalAmount
	stats.TransactionStats["transaction_count"] = transactionCount
	stats.TransactionStats["recharge_amount"] = rechargeAmount

	return nil
}

// calculateAccountBalance 计算账户余额
func (s *StatisticsService) calculateAccountBalance(ctx context.Context, platformInfo *middleware.PlatformInfo, stats *HlPayEnhancedStatistics) error {
	// 从HlPay账户余额表获取账户余额
	var accountBalances []models.HlPayAccountBalance
	query := database.DB

	if strings.HasPrefix(platformInfo.MatrixAccount, "SUB") {
		// 子账号用户，只能看到自己的账户
		query = query.Where("owner_no = ?", platformInfo.MatrixAccount)
	} else {
		// 主账号用户，可以看到所有子账号的账户
		query = query.Where("owner_no = ? OR owner_no LIKE ?",
			platformInfo.MatrixAccount, platformInfo.MatrixAccount+"%")
	}

	if err := query.Find(&accountBalances).Error; err != nil {
		return fmt.Errorf("failed to get account balances: %v", err)
	}

	// 计算总账户余额
	var totalAccountBalance float64
	for _, balance := range accountBalances {
		totalAccountBalance += balance.RealTimeBalance.InexactFloat64()
	}

	stats.AccountBalance = totalAccountBalance
	stats.TransactionStats["account_balance"] = totalAccountBalance

	return nil
}

// calculateMonthlyChargebackRate 计算当月拒付率
func (s *StatisticsService) calculateMonthlyChargebackRate(ctx context.Context, platformInfo *middleware.PlatformInfo, stats *HlPayEnhancedStatistics) error {
	// 获取当月时间范围
	now := time.Now()
	startOfMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
	endOfMonth := startOfMonth.AddDate(0, 1, 0).Add(-time.Second)

	// 获取用户ID列表
	var userIDs []int64
	query := database.DB.Model(&models.UserMatrixAccount{}).Select("user_id")

	if strings.HasPrefix(platformInfo.MatrixAccount, "SUB") {
		query = query.Where("matrix_account = ?", platformInfo.MatrixAccount)
	} else {
		query = query.Where("matrix_account = ? OR matrix_account LIKE ?",
			platformInfo.MatrixAccount, platformInfo.MatrixAccount+"%")
	}

	if err := query.Find(&userIDs).Error; err != nil {
		return fmt.Errorf("failed to get user IDs: %v", err)
	}

	// 统计当月交易和拒付
	var totalTransactions int64
	var chargebackTransactions int64

	for _, userID := range userIDs {
		userTxListKey := fmt.Sprintf("hlpay_user_transactions:%d", userID)
		txIDs, err := database.RedisClient.ZRange(ctx, userTxListKey, 0, -1).Result()
		if err != nil {
			continue
		}

		for _, txID := range txIDs {
			txKey := fmt.Sprintf("hlpay_transaction:%s", txID)
			txData, err := database.Get(ctx, txKey)
			if err != nil {
				continue
			}

			var tx struct {
				TransactionTime string `json:"transactionTime"`
				Status          string `json:"status"`
			}
			if err := json.Unmarshal([]byte(txData), &tx); err != nil {
				continue
			}

			// 解析交易时间
			txTime, err := time.Parse("2006-01-02 15:04:05", tx.TransactionTime)
			if err != nil {
				continue
			}

			// 检查是否在当月
			if txTime.After(startOfMonth) && txTime.Before(endOfMonth) {
				totalTransactions++

				// 检查是否为拒付交易
				if strings.ToLower(tx.Status) == "chargeback" || strings.Contains(strings.ToLower(tx.Status), "chargeback") {
					chargebackTransactions++
				}
			}
		}
	}

	// 计算拒付率
	if totalTransactions > 0 {
		stats.ChargebackRate = float64(chargebackTransactions) / float64(totalTransactions) * 100
	} else {
		stats.ChargebackRate = 0
	}

	stats.TransactionStats["monthly_transactions"] = totalTransactions
	stats.TransactionStats["monthly_chargebacks"] = chargebackTransactions
	stats.TransactionStats["chargeback_rate"] = stats.ChargebackRate

	return nil
}

// SimplifiedCardStatistics 简化的卡片统计数据，用于卡列表接口
type SimplifiedCardStatistics struct {
	TotalCards          int64   `json:"total_cards"`           // 总卡片数
	ActiveCards         int64   `json:"active_cards"`          // 活跃卡片数
	FrozenCards         int64   `json:"frozen_cards"`          // 冻结卡片数
	TotalBalance        float64 `json:"total_balance"`         // 总余额
	TotalTransferAmount float64 `json:"total_transfer_amount"` // 总转账金额
	TotalConsumption    float64 `json:"total_consumption"`     // 累计消费（总转账金额 - 总余额）
	UserAccountBalance  float64 `json:"user_account_balance"`  // 用户账户余额
}

// GetSimplifiedCardStatistics 获取简化的卡片统计数据
func (s *StatisticsService) GetSimplifiedCardStatistics(ctx context.Context, platformInfo *middleware.PlatformInfo) (*SimplifiedCardStatistics, error) {
	return s.GetSimplifiedCardStatisticsWithBalance(ctx, platformInfo, 0, 0, 0, 2) // 默认普通用户角色
}

// GetSimplifiedCardStatisticsWithBalance 获取简化的卡片统计数据，支持传入预计算的总余额和总转账金额
func (s *StatisticsService) GetSimplifiedCardStatisticsWithBalance(ctx context.Context, platformInfo *middleware.PlatformInfo, preCalculatedBalance float64, preCalculatedTransferAmount float64, userID int64, roleID int64) (*SimplifiedCardStatistics, error) {
	// 生成缓存key
	cacheKey := fmt.Sprintf("simplified_card_stats:%s", platformInfo.MatrixAccount)

	// 尝试从Redis获取缓存数据
	cachedData, err := database.Get(ctx, cacheKey)
	if err == nil && cachedData != "" {
		var stats SimplifiedCardStatistics
		if err := json.Unmarshal([]byte(cachedData), &stats); err == nil {
			// 如果传入了预计算的总余额，使用它覆盖缓存中的余额
			if preCalculatedBalance > 0 {
				stats.TotalBalance = preCalculatedBalance
			}
			// 如果传入了预计算的总转账金额，使用它覆盖缓存中的转账金额
			if preCalculatedTransferAmount > 0 {
				stats.TotalTransferAmount = preCalculatedTransferAmount
			}
			return &stats, nil
		}
	}

	// 缓存未命中，从数据库获取数据
	var userCards []models.UserCard
	query := database.DB.Where("platform = ?", platformInfo.PlatformType)

	// 根据矩阵账户过滤数据
	if strings.HasPrefix(platformInfo.MatrixAccount, "SUB") {
		// 子账号用户，只能看到自己的卡片
		query = query.Where("user_id IN (SELECT user_id FROM user_matrix_accounts WHERE matrix_account = ?)", platformInfo.MatrixAccount)
	} else {
		// 主账号用户，可以看到所有子账号的卡片
		query = query.Where("user_id IN (SELECT user_id FROM user_matrix_accounts WHERE matrix_account = ? OR matrix_account LIKE ?)",
			platformInfo.MatrixAccount, platformInfo.MatrixAccount+"%")
	}

	if err := query.Find(&userCards).Error; err != nil {
		return nil, fmt.Errorf("failed to get user cards from database: %v", err)
	}

	// 统计卡片数量和余额
	var stats SimplifiedCardStatistics
	stats.TotalCards = int64(len(userCards))

	// 如果传入了预计算的总余额，使用它；否则从数据库计算
	if preCalculatedBalance > 0 {
		stats.TotalBalance = preCalculatedBalance
	} else {
		for _, card := range userCards {
			// 统计余额（TotalTransferAmount字段）
			balance := card.TotalTransferAmount.InexactFloat64()
			stats.TotalBalance += balance
		}
	}

	// 如果传入了预计算的总转账金额，使用它；否则从数据库计算
	if preCalculatedTransferAmount > 0 {
		stats.TotalTransferAmount = preCalculatedTransferAmount
	} else {
		for _, card := range userCards {
			// 统计总转账金额（TotalTransferAmount字段）
			transferAmount := card.TotalTransferAmount.InexactFloat64()
			stats.TotalTransferAmount += transferAmount
		}
	}

	// 统计各状态卡片数量
	for _, card := range userCards {
		switch strings.ToLower(card.CardStatus) {
		case "normal":
			stats.ActiveCards++
		case "frozen":
			stats.FrozenCards++
		}
	}

	// 获取用户账户余额
	var userAccountBalance float64
	if userID > 0 {
		switch roleID {
		case 3: // 主账号
			var masterAccount models.MasterAccount
			if err := database.DB.Where("user_id = ?", userID).First(&masterAccount).Error; err == nil {
				userAccountBalance = masterAccount.Balance.InexactFloat64()
			}
		case 5: // 子账号
			var subAccount models.SubAccount
			if err := database.DB.Where("user_id = ?", userID).First(&subAccount).Error; err == nil {
				userAccountBalance = subAccount.Balance.InexactFloat64()
			}
		case 2: // 普通用户
			// 对于PhotonPay平台，尝试获取账户余额
			if platformInfo.PlatformType == "photonpay" {
				var userMatrixAccount models.UserMatrixAccount
				if err := database.DB.Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount).Error; err == nil {
					// 调用PhotonPay API获取账户余额
					params := photonpayModels.AccountListQueryParams{
						MatrixAccount: userMatrixAccount.MatrixAccount,
					}

					accountList, err := services.GetAccountList(ctx, s.client, params)
					if err == nil && accountList.Data != nil && len(accountList.Data) > 0 {
						// 获取第一个账户的余额作为用户账户余额
						userAccountBalance = accountList.Data[0].RealTimeBalance
					} else {
						// 如果API调用失败，使用矩阵账户的TotalTransferAmount作为备选
						userAccountBalance = userMatrixAccount.TotalTransferAmount.InexactFloat64()
					}
				}
			}
		}
	}

	// 设置用户账户余额
	stats.UserAccountBalance = userAccountBalance

	// 计算累计消费（总转账金额 - 总余额），使用decimal确保精度
	// 将float64转换为decimal进行计算
	transferAmountDecimal := decimal.NewFromFloat(stats.TotalTransferAmount)
	balanceDecimal := decimal.NewFromFloat(stats.TotalBalance)
	consumptionDecimal := transferAmountDecimal.Sub(balanceDecimal)

	// 将结果转换回float64，保留2位小数
	stats.TotalConsumption = consumptionDecimal.Round(2).InexactFloat64()

	// 将数据缓存到Redis，设置30秒的过期时间
	if data, err := json.Marshal(stats); err == nil {
		database.SetWithExpiration(ctx, cacheKey, data, 30*time.Second)
	}

	return &stats, nil
}
